<template>
  <div>
    <div v-bind:id="myClass"></div>
  </div>
</template>

<script setup lang="ts">
import { watch } from "vue";
import { defineComponent, onMounted, onUnmounted, ref } from "vue";
import E from "wangeditor";

let editor: any; // 使用 ref 来引用编辑器

function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdefe";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return "editor"+uuid;
}

const myClass=ref(uuid())

const getText=()=>{
  return editor.txt.text()
}

const add = () => {
  // console.log(editor.txt.text())
  return editor.txt.html()
};

const setValue=(value:string)=>{
    // console.log(value)
    editor.txt.html(value+'')
}

const props=defineProps<{
  text?:string;
}>()

watch(props,(newValue)=>{
  if(props.text!==undefined)
  {
    editor.txt.html(newValue.text)
  }
})

onMounted(() => {
  editor = new E(`#${myClass.value}`);
  editor.config.height = 120;

  var menus = [
    "head",
    "bold",
    "fontSize",
    "fontName",
    "italic",
    "underline",
    "strikeThrough",
    "indent",
    "lineHeight",
    "foreColor",
    "backColor",
    "link",
    "list",
    "justify",
    "quote",
    "image",
    "table",
    "code",
    "splitLine",
    "undo",
    "redo",
  ];

  editor.config.menus = menus;

  editor.config.uploadImgServer = "/iPDMessage/saveImg";

  editor.create();

  if(props.text!==undefined)
  {
    editor.txt.html(props.text)
  }

  // setValue('ppp')
});

// const 
defineExpose({
  add,
  setValue,
  getText
})



onUnmounted(() => {
  if (editor == null) return;
  editor.destroy();
});
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" >
.w-e-toolbar {
  z-index: 2!important;
}
.w-e-menu {
  z-index: 2 !important;
}
.w-e-text-container {
  z-index: 1 !important;
}

.text {
  border: 1px solid #ccc;
  max-height: 120px;
}
</style>
